import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
import { getUnreadCount } from '../api/message';
import { useAuth } from './AuthContext';

interface MessageContextType {
  unreadCount: number;
  refreshUnreadCount: () => Promise<void>;
  decreaseUnreadCount: (count?: number) => void;
}

const MessageContext = createContext<MessageContextType | undefined>(undefined);

export const useMessage = () => {
  const context = useContext(MessageContext);
  if (context === undefined) {
    throw new Error('useMessage must be used within a MessageProvider');
  }
  return context;
};

interface MessageProviderProps {
  children: ReactNode;
}

export const MessageProvider: React.FC<MessageProviderProps> = ({ children }) => {
  const [unreadCount, setUnreadCount] = useState(0);
  const { isAuthenticated } = useAuth();

  const refreshUnreadCount = useCallback(async () => {
    if (!isAuthenticated) {
      setUnreadCount(0);
      return;
    }

    try {
      const response = await getUnreadCount();
      if (response?.code === 200) {
        setUnreadCount(response.data || 0);
      }
    } catch (error) {
      console.error('获取未读消息数量失败:', error);
      // 静默失败，不影响用户体验
    }
  }, [isAuthenticated]);

  const decreaseUnreadCount = (count: number = 1) => {
    setUnreadCount(prev => Math.max(0, prev - count));
  };

  useEffect(() => {
    let interval: NodeJS.Timeout | null = null;

    if (isAuthenticated) {
      refreshUnreadCount();
      // 每60秒刷新一次未读消息数量
      interval = setInterval(refreshUnreadCount, 60000);
    } else {
      setUnreadCount(0);
    }

    // 清理函数
    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [isAuthenticated, refreshUnreadCount]);

  const value: MessageContextType = {
    unreadCount,
    refreshUnreadCount,
    decreaseUnreadCount,
  };

  return (
    <MessageContext.Provider value={value}>
      {children}
    </MessageContext.Provider>
  );
}; 